package com.weijing.pretty_app.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import androidx.fragment.app.Fragment
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R
import com.weijing.pretty_app.adapter.UserAdapter
import com.weijing.pretty_app.databinding.FragmentUserBinding
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.ToastUtils
import com.weijing.pretty_app.util.UserRepository

/**
 * user fragment 用户页面
 */
class UserFragment : Fragment() {

    private lateinit var binding: FragmentUserBinding
    private var listData: MutableList<UserModel> = mutableListOf()
    private var adapter: UserAdapter? = null
    private var openFlag = true //true== open false==edit
    private var selectData: UserModel? = null

    //selectUser==true代表左侧 false 代表右侧数据
    private var selectUser: Boolean? = null
    private var nenFuSelectUser: Boolean? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentUserBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initAdapter()
        updateData()
        binding.handleFragmentClWindowBack.setOnClickListener {
            binding.userFragmentLlWindow.visibility = View.GONE
            clearWindowValue()
        }

        binding.userFragmentClAdd.setOnClickListener {
            binding.handleFragmentTvId.visibility = View.GONE
            binding.userFragmentLlWindow.visibility = View.VISIBLE
            openFlag = true
        }

        //保存结束
        binding.handleFragmentClWindowSave.setOnClickListener {
            val name = binding.handleFragmentEtName.text.toString().trim()
            val phone = binding.handleFragmentEtPhone.text.toString().trim()
            val selectedId = binding.handleFragmentRadioGroupGender.checkedRadioButtonId

            // 判断是否有选择
            val gender = if (selectedId != -1) {
                val selectedRadioButton = requireView().findViewById<RadioButton>(selectedId)
                selectedRadioButton.text.toString() // 获取显示的性别文本，例如 "男" 或 "女"
            } else {
                null // 用户还未选择
            }
            val address = binding.handleFragmentEtAddress.text.toString().trim()
            if (name.isNullOrEmpty()) {
                ToastUtils.show("User Name" + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }
            if (gender.isNullOrEmpty()) {
                ToastUtils.show("User Gender" + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }
            if (phone.isNullOrEmpty()) {
                ToastUtils.show("User Phone" + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }
            if (address.isNullOrEmpty()) {
                ToastUtils.show("User Address" + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }

            when (openFlag) {
                true -> {
                    UserRepository.addUser(name, gender, phone, address)
                }

                false -> {
                    UserRepository.updateUser(
                        UserModel(selectData?.id!!, name, gender, phone, address)
                    )
                }
            }

            CoreUtil.showTvCustomToast(binding.handleFragmentTvOk)
            updateData()
            binding.userFragmentLlWindow.visibility = View.GONE
            clearWindowValue()
        }

        LiveEventBus.get<Boolean>(KeyUtil.HOME_SELECT_USER).observeSticky(this, { flag ->
            selectUser = flag
        })

        LiveEventBus.get<Boolean>(KeyUtil.NENFU_HOME_SELECT_USER).observeSticky(this, { flag ->
            nenFuSelectUser = flag
        })
    }

    private fun updateData() {
        listData.clear()
        val all = UserRepository.getAllUsers()
        listData.addAll(all)
        adapter?.notifyDataSetChanged()
    }

    private fun initAdapter() {
        adapter = UserAdapter(listData)
        adapter?.onClickListener = object : UserAdapter.OnClickListener {
            override fun onItemClickListener(model: UserModel) {
                if (selectUser == true) {
                    LiveEventBus.get<Map<Boolean, UserModel>>(KeyUtil.HOME_SELECT_USER_VALUE).post(
                        mapOf(true to model)
                    )
                }
                if (selectUser == false) {
                    LiveEventBus.get<Map<Boolean, UserModel>>(KeyUtil.HOME_SELECT_USER_VALUE).post(
                        mapOf(false to model)
                    )
                }
                if (nenFuSelectUser == true) {
                    LiveEventBus.get<Map<Boolean, UserModel>>(KeyUtil.NENFU_HOME_SELECT_USER_VALUE).post(
                        mapOf(true to model)
                    )
                }
                if (nenFuSelectUser == false) {
                    LiveEventBus.get<Map<Boolean, UserModel>>(KeyUtil.NENFU_HOME_SELECT_USER_VALUE).post(
                        mapOf(false to model)
                    )
                }
                requireActivity().finish()
            }

            override fun onEditClick(model: UserModel) {
                openFlag = false
                selectData = model
                binding.userFragmentLlWindow.visibility = View.VISIBLE
                binding.handleFragmentTvId.visibility = View.VISIBLE
                //赋值
                binding.handleFragmentTvId.text = "User Id：${model.id}"
                binding.handleFragmentEtName.setText(model.name)
                when (model.gender) {
                    getString(R.string.male) -> {
                        binding.handleFragmentRadioGroupGender.check(R.id.handleFragment_radioMale)
                    }

                    getString(R.string.female) -> {
                        binding.handleFragmentRadioGroupGender.check(R.id.handleFragment_radioFemale)
                    }
                }
                binding.handleFragmentEtPhone.setText(model.phone)
                binding.handleFragmentEtAddress.setText(model.address)
            }

            override fun onDeleteClick(model: UserModel) {
                UserRepository.deleteUserById(model.id)
                updateData()
            }
        }
        binding.userFragmentRV.adapter = adapter
    }

    private fun clearWindowValue() {
        binding.handleFragmentEtName.setText("")
        binding.handleFragmentRadioGroupGender.clearCheck()
        binding.handleFragmentEtPhone.setText("")
        binding.handleFragmentEtAddress.setText("")
    }
}

data class UserModel(
    val id: Int,
    val name: String,
    val gender: String,//Male Female
    val phone: String,
    val address: String,
    var treatmentTimes: Int? = null,
    var treatmentDate: String? = "",
    var intensityValue: Int? = null,
    var durationValue: Int? = null,
    var FrequencyValue: Int? = null
)